import json
import logging

from base.request import ApiBaseHandler
from common.definition import OrderStatus, ret_msg

logger = logging.getLogger("wechat")


class AfterSale(ApiBaseHandler):
    async def post(self, order_id):
        ip = self.request.remote_ip
        open_id = await self.get_open_id()
        # 售后类型（1=退货，2=换货）
        as_type = self.get_argument("type", None)
        reason = self.get_argument("reason", "")
        logger.info("售后申请：oid=%s,order_id=%s,type=%s,reason=%s,ip=%s" % (open_id, order_id, as_type, reason, ip))
        if as_type not in ["1", "2"]:
            return self.finish(ret_msg(-1, error_message="售后类型错误"))

        class GoodsOrder(object):
            pass

        session = self.get_db_session([
            {"db_table": "sdet_order", "model": GoodsOrder},
        ])

        filters = dict(
            sdef_order_id=order_id,
        )
        device_id = self.get_argument("device_id", None)
        if device_id:
            filters["sdef_order_describe"] = open_id
        else:
            filters["sdef_order_device_id"] = open_id

        o = session.query(GoodsOrder).filter_by(**filters).one()
        # 7天内的已收货订单才能申请售后(7天后会自动计算收益并且完成订单)
        if o.sdef_order_status != OrderStatus.RECEIVED:
            session.close()
            return self.finish(ret_msg(-1, error_message="已收货的订单才能申请售后"))

        o.sdef_order_status = OrderStatus.AFTER_SALE
        o.sdef_order_after_sale_type = as_type
        o.sdef_order_after_sale_status = 1
        sale_info = dict(
            reason=reason,
        )
        o.sdef_order_after_sale_info = json.dumps(sale_info)
        session.commit()
        session.close()
        return self.finish(ret_msg())


class AfterSaleStatus(ApiBaseHandler):
    async def post(self, order_id):
        ip = self.request.remote_ip
        open_id = await self.get_open_id()
        status = self.get_argument("status", None)
        logger.info("售后状态变更：open_id=%s,order_id=%s,status=%s,ip=%s" % (open_id, order_id, status, ip))
        if status not in ["3", "6"]:
            return self.finish(ret_msg(-1, error_message="不支持的状态类型"))

        class GoodsOrder(object):
            pass

        filters = dict(
            sdef_order_id=order_id,
        )
        device_id = self.get_argument("device_id", None)
        if device_id:
            filters["sdef_order_describe"] = open_id
        else:
            filters["sdef_order_device_id"] = open_id

        session = self.get_db_session([
            {"db_table": "sdet_order", "model": GoodsOrder},
        ])
        o = session.query(GoodsOrder).filter_by(**filters).one()
        old_status = o.sdef_order_after_sale_status
        if status == "3":
            if old_status != 2:
                session.close()
                return self.finish(ret_msg(-1, error_message="状态异常"))
            express_name = self.get_argument("express_name")
            express_no = self.get_argument("express_no")
            remarks = self.get_argument("remarks")
            old_sale_info = json.loads(o.sdef_order_after_sale_info)
            old_sale_info["express_name"] = express_name
            old_sale_info["express_no"] = express_no
            old_sale_info["remarks"] = remarks
            o.sdef_order_after_sale_info = json.dumps(old_sale_info)
            o.sdef_order_after_sale_status = status
            session.commit()
        if status == "6":
            if old_status != 5:
                session.close()
                return self.finish(ret_msg(-1, error_message="状态异常"))
            if o.sdef_order_after_sale_type == 1:
                # 退货时为失效
                o.sdef_order_status = OrderStatus.INVALID
            else:
                # 换货时为完成
                o.sdef_order_status = OrderStatus.COMPLETE
            o.sdef_order_after_sale_status = status
            session.commit()
        session.close()
        return self.finish(ret_msg())
